package training.sample.app.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import training.sample.app.domain.UserAccount;
import training.sample.app.service.UserService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List; 

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    
	@Autowired
    private UserService userService;

	@Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
    	
    	UserAccount user = userService.loadUserDetailsByLogin(login);
        
        if (user == null) {
            throw (new UsernameNotFoundException("User " + login + " not found"));
        }

        ApplicationUserDetails appUserDetails = 
        		new ApplicationUserDetails(user, getAuthorities(user));
        
        return appUserDetails;
    }
	
	protected Collection<GrantedAuthority> getAuthorities(UserAccount user) {
	    
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
		authList.add(new SimpleGrantedAuthority("ROLE_" + user.getRole().toString()));
	    
	    return authList;
	}
} 
